var express = require('express');
var router = express.Router();
var {Users} = require('../utils/model')
var {startEncrypt , getDecrypt} = require('../utils/index')

// get  请求
// / 路由地址
// req 请求信息
// res 响应信息
// next 下一个中间件
// res.render 渲染模板

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});


//登录
router.post('/login', (req, res) => {
  var body = req.body;
  var username = body.username;
  var password = body.password;
  console.log(username,password);
  if(username&&password){
    Users.findOne({
      username
    }).then(result=>{
      if(result){
        if(result.password == password){
          //获取登录的信息
          
          req.session.username = result.username;
          req.session.logintime = new Date();
          req.session.token = startEncrypt(result.username) //判断用户是否登录

          res.redirect('/')   //登录成功  跳转页面   重定向
        }else{
          res.send("<script>alert('用户名或密码错误，请重新输入');location.href='/login'</script>")
        }
      }else{
        res.send("<script>alert('用户名不存在，请重新登录');location.href='/login'</script>")
      }
    })
  }else{
    res.send("<script>alert('用户名或密码是必填字段，请重新输入');location.href='/login'</script>")
  }
});


//注册
router.post('/register', (req, res) => {
  var body = req.body;
  console.log(body);
  var username = body.username;
  var password = body.password;
  if(username&&password){
    Users.findOne({
      username
    }).then(result=>{
      console.log(result);
      if(result){
        console.log("用户名已被注册，请重新注册")
        res.send("<script>alert('用户名已被注册，请重新注册');location.href='/register'</script>")
      }else{
        body.time = new Date()
        Users.insertMany({
          username,
          password
        }).then(data=>{
          res.send(`<script>alert('注册成功，跳转到登录');location.href='/login?username=${startEncrypt(username)}'</script>`)
        })
      }
    })
  }else{
    console.log("111")
    res.send("<script>alert('用户名或者密码是必填字段，请重新填写');location.href='/register'</script>")   
  }
});


//修改密码

router.post('/changepass',(req,res)=>{
  var body = req.body;
  console.log(body);
  var username = req.session.username 
  console.log(username);
  Users.findOne({
    username
  }).then(result=>{
    if(result.password === body.oldpassword && body.newpassword){
      Users.updateMany({
        username
      },{
        $set:{
          password:body.newpassword
        }
      }).then(result=>{
        res.send("<script>alert('修改密码成功');location.href='/login'</script>")   
      })
    }else{
      res.send("<script>alert('输入密码错误，请重新填写');location.href='/changepass'</script>")   
    }
  })
})



module.exports = router;
